
package com.sausageking.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Strings;
import com.googlecode.objectify.NotFoundException;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;
import com.sausageking.server.common.ServerUtil;
import com.sausageking.server.dao.GenericDao;
import com.sausageking.shared.BaseUtil;
import com.sausageking.shared.Constants;

@Deprecated
public class FacebookAuthServlet extends HttpServlet {

  private static final long serialVersionUID = 1769210108707791802L;

  private static final Logger log = Logger.getLogger(FacebookAuthServlet.class
      .getName());

  private static final BaseUtil authUtil = new ServerUtil();

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    log.info(req.getRequestURI());
    log.info(req.getQueryString());
    String page = req.getParameter("page");
    String place = req.getParameter("place");
    String token = req.getParameter("token");
    String authToken = req.getParameter("code");
    String fbAuthError = req.getParameter("error_reason");
    if (!Strings.isNullOrEmpty(authToken)) {
      log.info("authtoken: " + authToken);
      String accessToken = getAccessToken(authToken, page, place, token);
      User user = getUser(accessToken);
      storeUser(user, accessToken);
      String redirectUrl = getRedirectUrl(page, place, token, user, accessToken);
      log.info("redirect to " + redirectUrl);
      resp.sendRedirect(redirectUrl);
    } else if (!Strings.isNullOrEmpty(fbAuthError)) {
      resp.sendRedirect("/");
    }
  }

  private String getRedirectUrl(String page, String place, String token,
      User user, String accessToken) {
    if (!Strings.isNullOrEmpty(page) && page.indexOf('/') == 0) {
      page = page.substring(1);
    }
    return "/" + page + "?" + Constants.USER + "=" + user.getId() + "&"
        + Constants.ACCESS_TOKEN + "=" + accessToken + "&" + Constants.NAME
        + "=" + user.getName() + "#" + place + ":" + token;
  }

  private void storeUser(User fbUser, String accessToken) {
    log.info(fbUser.toString());

    com.sausageking.shared.Consumer user = new com.sausageking.shared.Consumer();
    //user.(fbUser.getId());
    user.setEmail(fbUser.getEmail());
    user.setAccessToken(accessToken);
    // user.setLocation(fbUser.getLocation());
    GenericDao<com.sausageking.shared.Consumer> dao = new GenericDao<com.sausageking.shared.Consumer>(
        com.sausageking.shared.Consumer.class);
    try {
      com.sausageking.shared.Consumer loadedUser = new com.sausageking.shared.Consumer(); //= dao.get(user.getId());
      loadedUser.setAccessToken(accessToken);
      log.info("update access token: " + loadedUser.getAccessToken() + " to "
          + accessToken);
      dao.put(loadedUser);
    } catch (NotFoundException e) {
      log.info("store new user: " + user);
      dao.put(user);
    }

    log.info(fbUser.toString());
    log.info("store user: " + user);
    dao.put(user);
  }

  private User getUser(String accessToken) {
    FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
    User user = facebookClient.fetchObject("me", User.class);
    log.info("fetch user: " + user.toString());
    return user;
  }

  private String getAccessToken(String authToken, String page, String place,
      String token) throws UnsupportedEncodingException {
    String url = authUtil.getFacebookAccessTokenUrl(authToken, page, place,
        token);
    log.info("fetch access token from " + url);
    String response = Util.fetchURL(url);
    log.info("response: " + response);
    String parts[] = response.split("&");
    String accessTokenPair = parts[0];
    parts = accessTokenPair.split("=");
    String accessToken = (parts.length < 2) ? "" : parts[1];
    log.info("access token: " + accessToken);
    return accessToken;
  }
}
